﻿using Basic.HrCollect;
using Basic.HrRemoteModel;
using Basic.HrRemoteModel.Holidays.Model;
using Basic.HrService.Interface;
using Basic.HrService.Model;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.Http;

namespace Basic.HrService.Extend
{
    internal class SyncHolidaysService : ISyncHolidaysService
    {
        private readonly IHolidaysCollect _Holidays;
        private static readonly string _HolidaysKey = "Holidays";
        public SyncHolidaysService ( IHolidaysCollect holidays )
        {
            this._Holidays = holidays;
        }
        static SyncHolidaysService ()
        {
            _ = HttpClientFactory.AddClient(_HolidaysKey, client =>
            {
                client.AllowAutoRedirect = false;
                client.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
            });
        }
        public void Refresh ()
        {
            int year = DateTime.Now.Year;
            using ( HttpClient client = HttpClientFactory.Create(_HolidaysKey) )
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                Uri uri = new Uri("https://api.jiejiariapi.com/v1/holidays/" + year);
                HttpResult result = client.SendGet(uri, HttpCompletionOption.ResponseContentRead);
                Dictionary<string, HolidaysModel> holidays = result.GetObject<Dictionary<string, HolidaysModel>>();
                HolidaysAdd[] adds = holidays.ConvertAll(c =>
                {
                    return new HolidaysAdd
                    {
                        Date = DateTime.Parse(c.Key),
                        IsWork = c.Value.isOffDay == false,
                        Show = c.Value.name,
                        LimitSex = HrUserSex.未知,
                        TimeSpan = TimeSpanType.全天
                    };
                }).Add(new HolidaysAdd
                {
                    Date = new DateTime(year, 3, 8),
                    IsWork = true,
                    LimitSex = HrUserSex.女,
                    Show = "妇女节",
                    TimeSpan = TimeSpanType.下午
                });
                this._Holidays.Sync(year, adds);
            }
        }
    }
}
